package com.liuqianfei.markme.render;

import com.liuqianfei.markme.IRender;
import com.liuqianfei.markme.Renderer;
import com.liuqianfei.markme.common.Utils;
import com.liuqianfei.markme.core.Configuration;
import com.liuqianfei.markme.core.Token;
import com.liuqianfei.markme.rules.Environment;
import com.liuqianfei.util.StringUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liuqianfei
 */
public class FenceRender implements IRender
{
    @Override
    public String render(List<Token> tokens, int idx, Configuration configuration, Environment env, Renderer renderer)
    {
        Token token = tokens.get(idx);
        Token tmpToken = new Token();

        String info = StringUtil.isNotEmpty(token.info) ? Utils.unescapeAll(token.info).trim() : "";
        String langName = "";
        String highlighted = "";

        Map<String, String> tmpAttrs;

        if (StringUtil.isNotEmpty(info))
        {
            langName = info.split("\\s+")[0];
        }

        if (configuration.highlight)
        {
            // TODO
//            highlighted = configuration.highlight(token.content, langName) || Utils.escapeHtml(token.content);
        }
        else
        {
            highlighted = Utils.escapeHtml(token.content);
        }

        if (highlighted.indexOf("<pre") == 0)
        {
            return highlighted + '\n';
        }

        // If language exists, inject class gently, without mudofying original token.
        // May be, one day we will add .clone() for token and simplify this part, but
        // now we prefer to keep things local.
        if (StringUtil.isNotEmpty(info))
        {
            tmpAttrs = (null != token.attrs) ? token.attrs : new HashMap<>();

            tmpAttrs.put("class", configuration.langPrefix + langName);

            // Fake token just to render attributes
            tmpToken.attrs = tmpAttrs;

            return  "<pre><code" + renderer.renderAttrs(tmpToken) + ">"
                    + highlighted
                    + "</code></pre>\n";
        }

        return  "<pre><code" + renderer.renderAttrs(token) + ">"
                + highlighted
                + "</code></pre>\n";
    }
}
